package com.jd.mskill.controller;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.jd.mskill.config.CommonConstants;
import com.jd.mskill.config.LaiTeKe;
import com.jd.mskill.config.R;
import com.jd.mskill.mapper.SysPhoneMapper;
import com.jd.mskill.mapper.SysTokenMapper;
import com.jd.mskill.po.SysPhone;
import com.jd.mskill.po.SysToken;
import com.jd.mskill.utils.UserNameUtils;
import com.jd.mskill.utils.Utils;
import io.swagger.models.auth.In;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.net.URLDecoder;
import java.util.Date;

@RestController
@Slf4j
@RequestMapping("/sms")
public class ZmdSmsController {

    @Resource
    private SysTokenMapper sysTokenMapper;

    @Resource
    private SysPhoneMapper sysPhoneMapper;


    @Autowired
    private LaiTeKe laiTeKe;

    public static Integer PHONE_TIMES = 10;

    @GetMapping("/phone")
    public R phone() throws Exception {
        SysPhone sysPhone = getPhone(0);
        if (ObjectUtil.isNull(sysPhone)) {
            return R.failed();
        }
        return R.ok(sysPhone);
    }


    private SysPhone getPhone(Integer times) throws Exception {
        times = times + 1;
        if (times >= PHONE_TIMES) {
            return null;
        }
        //http://api.zmdsms.com/GetPhone/?id=项目ID&token=登录返回token
        SysToken sysToken = sysTokenMapper.selectOne(Wrappers.<SysToken>lambdaQuery().eq(SysToken::getDelFlag, 0));
        String token_url = String.format("http://api.zmdsms.com/GetPhone/?id=%s&token=%s", "16883", sysToken.getToken());
//        http://laiket.cn:7777/get?user=用户名&pwd=密码&type=项目 ID&phone=手机号&developer=开发者账号 ID
        //如果首次检测不通过，拉黑换号从新弄
//        http://laiket.cn:7777/get?user=用户名&pwd=密码&type=项目 ID&phone=手机号&developer=开发者账号 ID
        log.info("");
        HttpResponse execute = HttpRequest.get(token_url).timeout(2000).execute();
        //1|13000000000
        String body = execute.body();
        log.info("获取的原始数据为:{}", body);
        String[] msg_split = body.split("\\|");
        if (Integer.valueOf(msg_split[CommonConstants.ZERO]) == CommonConstants.ONE) {
            String phone = msg_split[CommonConstants.ONE];
            SysPhone sysPhone = new SysPhone(phone, new Date());
            try {
                sysPhoneMapper.insert(sysPhone);
            } catch (Exception e) {
                log.info("删除手机号码:{}",phone);
                //删除这个手机号码
                sysPhoneMapper.delete(Wrappers.<SysPhone>lambdaQuery().eq(SysPhone::getPhone,phone));
            }


            Integer cancel = isCancel(phone, sysToken, sysPhoneMapper);
            if (cancel == CommonConstants.ONE) {
                return getPhone(times);
            }
            //随机生成账号密码;
            String userName = UserNameUtils.getRandomPwd();
            String password = UserNameUtils.getRandomPwd();
            log.info("生成账号密码[ {},{} ]", userName, password);
            sysPhone.setUsername(userName);
            sysPhone.setPassword(password);
            sysPhoneMapper.updateById(sysPhone);
            log.info("生成的账号密码手机号为:[{}]", sysPhone);
            return sysPhone;
        } else {
            return getPhone(times);
        }
    }

    private Integer isCancel(String phone, SysToken sysToken, SysPhoneMapper sysPhoneMapper) {
        try {
            log.info("首次检查");
//        code:1001,msg:2
            String firstTest_url = String.format("http://laiket.cn:7777/get?user=%s&pwd=%s&type=%s&phone=%s", laiTeKe.getLai_te_ke_username(), laiTeKe.getLai_te_ke_password(), "10004", phone);
            HttpResponse firstTest_excute = HttpRequest.get(firstTest_url).header("Encoding", "UTF8").timeout(2000).execute();
            String firstTest_excute_context = URLDecoder.decode(firstTest_excute.body(), "utf-8");
//            code:1001,msg:1 //首次
            String firstTest_excute_context_one = firstTest_excute_context.split(",")[CommonConstants.ONE];
            String firstTest_excute_context_msg_one = firstTest_excute_context_one.split(":")[CommonConstants.ONE];
            if (Integer.valueOf(firstTest_excute_context_msg_one) != 1) {
                log.info("手机号不为1，释放手机号");
                String cancel_url = String.format("http://api.zmdsms.com/Addblack/?id=%s&phone=%s&token=%s", "16883", phone, sysToken.getToken());
                HttpRequest.get(cancel_url).timeout(2000).execute();
                SysPhone sysPhone = sysPhoneMapper.selectOne(Wrappers.<SysPhone>lambdaQuery().eq(SysPhone::getPhone, phone));
                if (ObjectUtils.isNotEmpty(sysPhone)) {
                    sysPhone.setIsCancel(CommonConstants.ONE);
                    sysPhoneMapper.updateById(sysPhone);
                }
                log.info("拉黑手机号成功:{}", phone);
                return CommonConstants.ONE;
            }
            return CommonConstants.ZERO;
        } catch (Exception e) {
            return CommonConstants.ZERO;
        }
    }

    //整个方法的逻辑是
    // 1、获取当前手机号码的短信，因为当前服务器数据返回有时候为空，
    // 所以循环5次。然后如果没有验证码就释放验证码
    @GetMapping("/phone/{phone}")
    public R phoneSms(@PathVariable("phone") String phone) throws Exception {
        HttpResponse execute = getSms(phone);
        //1|【京东】验证码为461433，请在注册页面中输入以完成注册
        //1|【京东】注册验证码：602909。京东客 服绝不会索取此验证码，切勿转发或告知他人。
        String[] msg_split = execute.body().split("\\|");
        Boolean flag = false;
        if (Integer.valueOf(msg_split[CommonConstants.ZERO]) != 1) {
            for (int i = 0; i < 10; i++) {
                execute = getSms(phone);
                msg_split = execute.body().split("\\|");
                //1|【京东】验证码为796076，请在注册页面中输入以完成注册
                if (Integer.valueOf(msg_split[CommonConstants.ZERO]) == CommonConstants.ONE) {
                    flag = true;
                    break;
                } else {
                    Thread.sleep(5000);
                }
            }
        } else {
            flag = true;
        }
        if (flag) {
            log.info("获取的原始数据为:{}", execute.body());
            if (Integer.valueOf(msg_split[CommonConstants.ZERO]) == CommonConstants.ONE) {
//            String context = "【京东】验证码为461433，请在注册页面中输入以完成注册";
                String code = Utils.getCode(execute.body());
                SysPhone sysPhone = sysPhoneMapper.selectOne(Wrappers.<SysPhone>lambdaQuery().eq(SysPhone::getPhone, phone).eq(SysPhone::getDelFlag, CommonConstants.ZERO));
                sysPhone.setCode(code);
                sysPhoneMapper.updateById(sysPhone);
                return R.ok(sysPhone);
            }
        } else {
            SysToken sysToken = sysTokenMapper.selectOne(Wrappers.<SysToken>lambdaQuery().eq(SysToken::getDelFlag, CommonConstants.ZERO));
            isCancel(phone, sysToken, sysPhoneMapper);
            return R.failed();
        }
        return R.failed();
    }

    private HttpResponse getSms(String phone) {
        //http://api.zmdsms.com/GetMsg/?id=项目ID&phone=手机号码&token=登录返回token
        SysToken sysToken = sysTokenMapper.selectOne(Wrappers.<SysToken>lambdaQuery().eq(SysToken::getDelFlag, CommonConstants.ZERO));
        String token_url = String.format("http://api.zmdsms.com/GetMsg/?id=%s&phone=%s&token=%s", "16883", phone, sysToken.getToken());
        log.info("获取短信验证码的url：{}", token_url);
        HttpResponse execute = HttpRequest.get(token_url).timeout(2000).execute();
        log.info("当前返回的数据是：{}", execute.body());
        return execute;
    }

    @GetMapping("/phone/sign/{phone}")
    public R phoneSmsSign(@PathVariable("phone") String phone) {
        SysPhone sysPhone = sysPhoneMapper.selectOne(Wrappers.<SysPhone>lambdaQuery().eq(SysPhone::getPhone, phone).eq(SysPhone::getDelFlag, CommonConstants.ZERO));
        sysPhone.setIsSign(CommonConstants.ONE);
        sysPhoneMapper.updateById(sysPhone);
        return R.ok();
    }


}
